package com.guchenbo.study.mvc.view;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.view.AbstractTemplateView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Map;

/**
 * Spring容器创建GcbView对象，使用Spring容器初始化对象，只是初始化不会依赖注入其他Bean
 *
 * @see org.springframework.web.servlet.view.UrlBasedViewResolver#createView(String, Locale)
 * @see org.springframework.web.servlet.view.UrlBasedViewResolver#loadView(String, Locale)
 * @see GcbViewResolver#getPrefix()
 * @see GcbViewResolver#getSuffix()
 */
public class GcbView extends AbstractTemplateView {
    protected static final Logger log = LoggerFactory.getLogger(GcbView.class);
    private ResourceHttpMessageConverter httpMessageConverter;

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        httpMessageConverter = new ResourceHttpMessageConverter();
    }

    @Override
    protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
                    HttpServletResponse response) throws Exception {
        Resource resource = getApplicationContext().getResource(getUrl());
        if (resource != null && resource.exists()) {
            log.info("resource exist = {}", resource.exists());
            String filename = resource.getFilename();
            MediaType mediaType = MediaTypeFactory.getMediaType(filename).orElse(null);

            ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
            httpMessageConverter.write(resource, mediaType, outputMessage);
        }
    }
}
